package com.example.prolyric.songmanager;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import android.app.Activity;
import android.database.Cursor;
import android.provider.MediaStore;

 public class SongsManager  {
	 /*
	  * CAC BIEN FINAL , PUBLIC DUNG CHUNG CHO CAC ACTIVITY
	  * MO TA KIEU PHAT HIEN TAI TUONG UNG VOI CAC GIA TRI INTEGER
	  * */
	 public static final int ALL_SONG = 0;
	 public static final int PLAY_LIST = 1;
	 public static final int TOP_RATE = 2;
	 public static final int  ALBUMS = 3;
	 public static final int  ARTISTS =4;
	 public static final int  GENERS = 5;
	 private static final String RATE_FILE = "rate_song.rpl";
	 private static final int toprate = 10;
	 
	 private   Activity activity;
	
	public SongsManager(Activity activity) {
		this.activity = activity;
	}
	
	
	
	public ArrayList<Song>getAllSong()
	{
		Cursor cursor;
		ArrayList<Song> songs =  null ;
		String[] columns = {
				MediaStore.Audio.Media.DATA,
				MediaStore.Audio.Media._ID,
				MediaStore.Audio.Media.TITLE,
				MediaStore.Audio.Media.DISPLAY_NAME,
				MediaStore.Audio.Media.MIME_TYPE,
				};
		
		
		//String whereVal[] = {cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM))};
		String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
		cursor = activity.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,columns, null, null, orderBy);
		
		if(cursor.moveToFirst())
		{
			songs = new ArrayList<Song>();
			do{
				Song s = new Song();
				s.setAudioFilePath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
				s.setSong_display_name(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
				songs.add(s);
			}while (cursor.moveToNext());
		}
		
		return songs;
		
	}
	
	
	public ArrayList<String> getAllAlbum()
	{
		
		ArrayList<String> listAlbum = null;
		String[] columns = {
    		android.provider.MediaStore.Audio.Albums._ID,
    		android.provider.MediaStore.Audio.Albums.ALBUM
    		};
	        Cursor cursor = activity.managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, columns,null, null, null);
	        if(cursor.moveToFirst())
	        {
	         listAlbum = new ArrayList<String>();
	        	do
	        	{
	        		listAlbum.add(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM)));
	        		
	        	}
	        	while(cursor.moveToNext());
	        }
		return listAlbum;
	}
	
	public ArrayList<String> getAllArtist()
	{
		ArrayList<String> listAlbum = null;
		String[] columns = {
    		android.provider.MediaStore.Audio.Artists._ID,
    		android.provider.MediaStore.Audio.Artists.ARTIST
    		};
	        Cursor cursor = activity.managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, columns,null, null, null);
	        if(cursor.moveToFirst())
	        {
	         listAlbum = new ArrayList<String>();
	        	do
	        	{
	        		listAlbum.add(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST)));
	        		
	        	}
	        	while(cursor.moveToNext());
	        }
		return listAlbum;
	}
	
	public ArrayList<Song> getSongsByAlbum(String albumName)
	{
		Cursor cursor;
		ArrayList<Song> songs =  null ;
		String[] columns = {
				MediaStore.Audio.Media.DATA,
				MediaStore.Audio.Media._ID,
				MediaStore.Audio.Media.TITLE,
				MediaStore.Audio.Media.DISPLAY_NAME,
				MediaStore.Audio.Media.MIME_TYPE,
				};
		String [] albumNames = {albumName};
		String where = android.provider.MediaStore.Audio.Media.ALBUM + "=?";
		//String whereVal[] = {cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM))};
		String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
		cursor = activity.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,columns, where, albumNames, orderBy);
		
		if(cursor.moveToFirst())
		{
			songs = new ArrayList<Song>();
			do{
				Song s = new Song();
				s.setAudioFilePath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
				s.setSong_display_name(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
				songs.add(s);
			}while (cursor.moveToNext());
		}
		
		return songs;
				
	}
	
	public ArrayList<Song> getSongsByType(String type, String name)
	{
		if(type.equals("Album"))
		{
			return getSongsByAlbum(name);
		}
		else return null;
	}
	
	

	public ArrayList<String>getAllPlaylists()
	{
		//File home = new File(this.activity.getFilesDir());
				File homePath = activity.getFilesDir();
				ArrayList<String> playlists = null;

				if (homePath.listFiles(new FileExtensionFilter()).length > 0) {
					playlists = new ArrayList<String>();
					for (File file : homePath.listFiles(new FileExtensionFilter())) {
						 
						playlists.add(file.getName());
					}
				}
				
				// return songs list array
				return playlists;		
		
	}

	public void savePlaylist(ArrayList<Song> playlist,String playlistName)
	{
		File HomePath = this.activity.getFilesDir();
		File playlistToSave = new File(HomePath,playlistName);
		
		try {
			
			FileOutputStream fos = new FileOutputStream(playlistToSave);
			DataOutputStream dos = new DataOutputStream(fos);
			dos.writeInt(playlist.size());
			dos.flush();
			for(int i = 0 ; i< playlist.size(); i++)
			{
				dos.writeUTF(playlist.get(i).getAudioFilePath());
				dos.writeUTF(playlist.get(i).getSong_display_name());
			}
			fos.flush();
			fos.close();
			dos.flush();
			dos.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Song> readContentOfPlaylist(String playlistName)
	{
		ArrayList<Song> content =null;
		
		
		File playlistFile = new File(this.activity.getFilesDir()+"/"+playlistName);
		
		
		
		if(!playlistFile.exists())
		{
			content =  null;
		}
		else
		{
			try {
				DataInputStream dis = new DataInputStream(new FileInputStream(playlistFile));
				int size = dis.readInt();
				content = new ArrayList<Song>();
				for(int i = 0 ; i< size; i++)
				{
					String audio_path = dis.readUTF();
					String name_display = dis.readUTF();
					content.add(new Song(audio_path, name_display));
					
				}
				dis.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			
		}
		return content;
	
	}
	
	public boolean  deletePlaylist(String playlistName)
	{
		boolean check = false ;
		File playlistToDel = new File(activity.getFilesDir()+"/"+playlistName);
		if(playlistToDel.exists())
		{
			try {
				check = playlistToDel.delete();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return check ; 
	}
	
	public void modifileRate(Song song, int rate)
	{
		ArrayList<RateItem> rateList = readContentOfRateFile();
		if(rateList == null)
		{
			saveRateFile(new ArrayList<RateItem>());
			rateList = new ArrayList<RateItem>();
		}
		
			
			
				int i = 0 ; 
				while(i<rateList.size())
				{
					if(rateList.get(i).getAudioFilePath().equals(song.getAudioFilePath())&&rateList.get(i).getSong_display_name().equals(song.getSong_display_name()))
					{
						rateList.get(i).setRate(rate);
						break;
					}
					i++;
				}
		
				if(i>=rateList.size())
				{

					RateItem newRate = new RateItem();
					newRate.setAudioFilePath(song.getAudioFilePath());
					newRate.setSong_display_name(song.getSong_display_name());
					newRate.setRate(rate);
					rateList.add(newRate);
				}
				
			
				
			
		saveRateFile(rateList);
		
	}
	
	
	public int getRateOfSong(Song s)
	{
		int rate = -1 ;
		ArrayList<RateItem> rateList = readContentOfRateFile();
		if(rateList == null)
			saveRateFile(new ArrayList<RateItem>());
		else{
			
			int i = 0 ; 
			while (i<rateList.size())
			{
				if(rateList.get(i).getAudioFilePath().equals(s.getAudioFilePath())&&rateList.get(i).getSong_display_name().equals(s.getSong_display_name()))
				{
					rate = rateList.get(i).getRate();
					break;
				}
			}
	
		}
		return rate;
	}
	
	public void saveRateFile(ArrayList<RateItem> ratelist)
	{
		File rateSong = new File(activity.getFilesDir()+RATE_FILE);
		if(!rateSong.exists())
		{
			rateSong = new File(activity.getFilesDir(),RATE_FILE);
		}
		
			try {
			
			FileOutputStream fos = new FileOutputStream(rateSong);
			DataOutputStream dos = new DataOutputStream(fos);
			dos.writeInt(ratelist.size());
			dos.flush();
			for(int i = 0 ; i< ratelist.size(); i++)
			{
				dos.writeUTF(ratelist.get(i).getAudioFilePath());
				dos.writeUTF(ratelist.get(i).getSong_display_name());
				dos.writeInt(ratelist.get(i).getRate());
			}
			fos.flush();
			fos.close();
			dos.flush();
			dos.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	public ArrayList<RateItem> readContentOfRateFile()
	{
		ArrayList<RateItem> content =null;
		
		
		File rateFile = new File(this.activity.getFilesDir()+"/"+RATE_FILE);
		
		
		
		if(!rateFile.exists())
		{
			content =  null;
		}
		else
		{
			try {
				DataInputStream dis = new DataInputStream(new FileInputStream(rateFile));
				int size = dis.readInt();
				content = new ArrayList<RateItem>();
				for(int i = 0 ; i< size; i++)
				{
					String audio_path = dis.readUTF();
					String name_display = dis.readUTF();
					int rate = dis.readInt();
					RateItem rateitem = new RateItem();
					rateitem.setAudioFilePath(audio_path);
					rateitem.setSong_display_name(name_display);
					rateitem.setRate(rate);
					content.add(rateitem);
					
					
				}
				dis.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			
		}
		return content;
	
	}
	
	
	public void deleteRateFile()
	{
		File rateFile = new File(this.activity.getFilesDir()+"/"+RATE_FILE);
		rateFile.delete();
	}
	
	public ArrayList<Song> getTopRate()
	{
		//File rateFile = new File(this.activity.getFilesDir()+"/"+RATE_FILE);
		ArrayList<RateItem> listRated = readContentOfRateFile();
		Collections.sort(listRated, new Comparator<RateItem>() {

			public int compare(RateItem lhs, RateItem rhs) {
				if(lhs.getRate()>rhs.getRate())
					return -1;
				else if(lhs.getRate()==rhs.getRate())
					return 0;
				else 
					return 1;
			}
		});
		ArrayList<Song> songs = new ArrayList<Song>();
		if(listRated.size()<TOP_RATE)
		{
			for(RateItem r : listRated)
			{
				songs.add(new Song(r.getAudioFilePath(), r.getSong_display_name()));
			}
		}
		else 
		{
			for(int i = 0 ; i<TOP_RATE ; i++)
			{
				songs.add(new Song(listRated.get(i).getAudioFilePath(), listRated.get(i).getSong_display_name()));
			}
		}
		return songs;
		
	}
	
	
	

}
 
 class FileExtensionFilter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			return (name.endsWith(".ppl") || name.endsWith(".ppl"));
		}
	}


